#!/usr/bin/env node

/**
 * 构建 npm 包的脚本
 * 将 d8d-admin-ui-deno 项目打包为 npm 包
 */

import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 项目根目录
const rootDir = path.resolve(__dirname, '..');
// 输出目录
const outDir = path.resolve(rootDir, 'npm');
// 临时目录
const tempDir = path.resolve(outDir, 'temp');

// 确保输出目录存在
if (!fs.existsSync(outDir)) {
  fs.mkdirSync(outDir, { recursive: true });
}

// 确保临时目录存在
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir, { recursive: true });
} else {
  // 清空临时目录
  fs.rmSync(tempDir, { recursive: true, force: true });
  fs.mkdirSync(tempDir, { recursive: true });
}

console.log('🚀 开始构建 npm 包...');

// 复制 package.json 并修改
console.log('📝 处理 package.json...');
const packageJson = JSON.parse(fs.readFileSync(path.resolve(rootDir, 'package.json'), 'utf-8'));

// 修改 package.json
delete packageJson.main;
delete packageJson.exports;
packageJson.type = 'module';
packageJson.main = './dist/index.js';
packageJson.module = './dist/index.js';
packageJson.types = './dist/index.d.ts';
packageJson.exports = {
  '.': {
    'types': './dist/index.d.ts',
    'import': './dist/index.js',
    'require': './dist/index.cjs',
  }
};
packageJson.files = ['dist'];

// 写入临时目录
fs.writeFileSync(
  path.resolve(tempDir, 'package.json'),
  JSON.stringify(packageJson, null, 2),
  'utf-8'
);

// 复制 README.md 和 LICENSE
console.log('📋 复制文档文件...');
if (fs.existsSync(path.resolve(rootDir, 'README.md'))) {
  fs.copyFileSync(
    path.resolve(rootDir, 'README.md'),
    path.resolve(tempDir, 'README.md')
  );
}

if (fs.existsSync(path.resolve(rootDir, 'LICENSE'))) {
  fs.copyFileSync(
    path.resolve(rootDir, 'LICENSE'),
    path.resolve(tempDir, 'LICENSE')
  );
}

// 复制源代码文件
console.log('📂 复制源代码文件...');
const copyDir = (src: string, dest: string) => {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const entries = fs.readdirSync(src, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      copyDir(srcPath, destPath);
    } else {
      // 跳过 node_modules 和 .git 目录
      if (srcPath.includes('node_modules') || srcPath.includes('.git')) {
        continue;
      }
      
      // 复制文件
      fs.copyFileSync(srcPath, destPath);
    }
  }
};

// 复制主要源代码目录
const dirsToCopy = ['component', 'hook', 'utils', 'types', 'pages'];
for (const dir of dirsToCopy) {
  const srcDir = path.resolve(rootDir, dir);
  const destDir = path.resolve(tempDir, dir);
  
  if (fs.existsSync(srcDir)) {
    copyDir(srcDir, destDir);
  }
}

// 复制主要文件
const filesToCopy = ['mod.ts', 'global.ts', 'constants.ts', 'style.css', 'tsconfig.json'];
for (const file of filesToCopy) {
  const srcFile = path.resolve(rootDir, file);
  const destFile = path.resolve(tempDir, file);
  
  if (fs.existsSync(srcFile)) {
    fs.copyFileSync(srcFile, destFile);
  }
}

// 创建 tsconfig.build.json 用于构建
console.log('📝 创建构建配置...');
const tsconfigBuild = {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./dist",
    "declaration": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "module": "ESNext",
    "target": "ES2020",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "allowImportingTsExtensions": true,
  },
  "include": ["mod.ts", "global.ts", "constants.ts", "component/**/*", "hook/**/*", "utils/**/*", "types/**/*", "pages/**/*"],
  "exclude": ["node_modules", "dist", "scripts"]
};

fs.writeFileSync(
  path.resolve(tempDir, 'tsconfig.build.json'),
  JSON.stringify(tsconfigBuild, null, 2),
  'utf-8'
);

// 创建入口文件
console.log('📄 创建入口文件...');
const indexContent = `
// 从 mod.ts 重新导出所有内容
export * from './mod';
`;

fs.writeFileSync(
  path.resolve(tempDir, 'index.ts'),
  indexContent,
  'utf-8'
);

// 使用 yarn 安装依赖
console.log('📦 安装依赖...');
process.chdir(tempDir);
execSync('yarn install', { stdio: 'inherit' });

// 添加构建依赖
console.log('📦 添加构建依赖...');
execSync('yarn add -D typescript @types/node esbuild', { stdio: 'inherit' });

// 创建构建脚本
const buildScript = `
import * as esbuild from 'esbuild';
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

// 编译 TypeScript 类型定义
console.log('🔨 编译 TypeScript 类型定义...');
execSync('npx tsc -p tsconfig.build.json', { stdio: 'inherit' });

// 使用 esbuild 构建 ESM 版本
console.log('🔨 构建 ESM 版本...');
esbuild.buildSync({
  entryPoints: ['index.ts'],
  bundle: true,
  format: 'esm',
  outfile: 'dist/index.js',
  external: Object.keys(JSON.parse(fs.readFileSync('package.json', 'utf-8')).dependencies || {}),
  platform: 'neutral',
  target: 'es2020',
  jsx: 'automatic',
  sourcemap: true,
});

// 使用 esbuild 构建 CJS 版本
console.log('🔨 构建 CJS 版本...');
esbuild.buildSync({
  entryPoints: ['index.ts'],
  bundle: true,
  format: 'cjs',
  outfile: 'dist/index.cjs',
  external: Object.keys(JSON.parse(fs.readFileSync('package.json', 'utf-8')).dependencies || {}),
  platform: 'neutral',
  target: 'es2020',
  jsx: 'automatic',
  sourcemap: true,
});

console.log('✅ 构建完成!');
`;

fs.writeFileSync(
  path.resolve(tempDir, 'build.mjs'),
  buildScript,
  'utf-8'
);

// 运行构建脚本
console.log('🔨 运行构建脚本...');
execSync('node build.mjs', { stdio: 'inherit' });

// 打包
console.log('📦 打包 npm 包...');
execSync('yarn pack', { stdio: 'inherit' });

// 将生成的 tgz 文件移动到输出目录
const tgzFiles = fs.readdirSync(tempDir).filter(file => file.endsWith('.tgz'));
if (tgzFiles.length > 0) {
  const tgzFile = tgzFiles[0];
  fs.renameSync(
    path.resolve(tempDir, tgzFile),
    path.resolve(outDir, tgzFile)
  );
  console.log(`✅ npm 包已生成: ${path.resolve(outDir, tgzFile)}`);
} else {
  console.error('❌ 未找到生成的 npm 包');
  process.exit(1);
}

// 清理临时目录
console.log('🧹 清理临时文件...');
fs.rmSync(tempDir, { recursive: true, force: true });

console.log('✨ 构建完成!'); 